<template>
    <section class="create-ad gg-create">
        <el-form ref="adCreate" :model="adCreate" :rules="rules" label-position="right" label-width="102px">
            <el-form-item label="广告形式：" class="adc-form">
                <div>文字</div>
                <div class="ad-form-gg">
                    <div v-if="edit != 'edit-ad'" class="content-btn-con">
                        <el-button :class="[{active: editIndex == index},'con-btn']" v-for="(item,index) in adCreate.content " @click="editIndex = index" :key="index" size="small" type="text">{{index+1}}</el-button>
                        <el-button class="plus-btn" v-show="adCreate.content.length < 3" @click="plusContent" icon="plus" size="small" type="primary"></el-button>
                        <el-button class="minus-btn" v-show="adCreate.content.length > 1" @click="minusContent" icon="minus" size="small" type="danger"></el-button>
                    </div>
                    <div class="content-con" v-for="(item,index) in adCreate.content" v-show="index == editIndex" :key="item.id">
                        <el-form-item label="最终到达网址" label-width="136px" :prop="'content.'+index+'.link'"
                                      :rules="[{required: true, message: '该项为必填项', trigger: 'blur'}]">
                            <el-input v-model="item.link" @blur="checkUrl(item.link,index)" placeholder=" "></el-input>
                        </el-form-item>
                        <el-form-item label="第一个标题" label-width="136px" :prop="'content.'+index+'.title1'"
                                      :rules="[{required: true, message: '该项为必填项', trigger: 'blur'}]">
                            <el-input class="lengthLimit" v-model="item.title1" @input="handleStringLen(item.title1,'adMaxLen['+index+'].title1',30,'content['+index+'].title1')" :maxlength="adMaxLen[index].title1"></el-input><span class="adc-tips stringCount"> {{item.title1 | returnLen30}}</span>
                        </el-form-item>
                        <el-form-item label="第二个标题" label-width="136px" :prop="'content.'+index+'.title2'"
                                      :rules="[{required: true, message: '该项为必填项', trigger: 'blur'}]">
                            <el-input class="lengthLimit" v-model="item.title2" @input="handleStringLen(item.title2,'adMaxLen['+index+'].title2',30,'content['+index+'].title2')" :maxlength="adMaxLen[index].title2"></el-input><span class="adc-tips stringCount"> {{item.title2 | returnLen30}}</span>
                        </el-form-item>
                        <el-form-item label="广告内容描述" label-width="136px" :prop="'content.'+index+'.description'"
                                      :rules="[{required: true, message: '该项为必填项', trigger: 'blur'}]">
                            <el-input class="lengthLimit" v-model="item.description" @input="handleStringLen(item.description,'adMaxLen['+index+'].desc',80,'content['+index+'].description')" :maxlength="adMaxLen[index].desc"></el-input><span class="adc-tips stringCount"> {{item.description | returnLen80}}</span>
                        </el-form-item>
                    </div>
                </div>
            </el-form-item>
            <el-form-item  label="广告预览：">
                <div class="adc-preview">
                    <div class="preview-header">
                        <el-select v-model="adCreate.preview" placeholder="请选择">
                            <el-option v-for="item in adPreviewPlatform" :key="item.id" :value="item"></el-option>
                        </el-select>
                        <div class="pagination">
                            第<span class="current">{{currentAdPage}}</span>/<span>{{totalAdPage}}</span>条广告
                            <el-button @click="pageChange('prev')" :class="{disable: currentAdPage === 1}" icon="arrow-left"></el-button>
                            <el-button @click="pageChange('next')" :class="{disable: currentAdPage >= totalAdPage}" icon="arrow-right"></el-button>
                        </div>
                    </div>
                    <div class="preview-body">
                        <google-pc :data="adPreviewData" v-if="adCreate.preview == '桌面版'"/>
                        <google-mb :data="adPreviewData" v-if="adCreate.preview == '移动版'"/>
                    </div>
                </div>
            </el-form-item>
            <div class="advance-setting ">
                <div class="bs-title "><span class="label">高级设置：</span><el-switch v-model="showMoreSetting" on-text="" off-text="" ></el-switch></div>
                <div v-show="showMoreSetting" class="bs-container">
                    <div class="adc-box">
                        <h3 class="adc-box-title">
                            <span class="iconfont icon-focus"></span>附加信息：
                            <span class="adc-box-name">添加附加信息，点击率有望提高多达<em class="color-red">15%</em></span>
                        </h3>
                    </div>
                    <ul class="adc-box-con">
                       <li>
                           <div class="left-title">
                                <el-checkbox v-model="checkFlag.link"></el-checkbox>
                               <span> 附加链接</span>
                               <el-tooltip content="附加链接可通过指向您网站特定页面的额外链接来扩展您的广告" placement="top" >
                                   <i class="iconfont icon-tip"></i>
                               </el-tooltip>
                           </div>
                           <div v-show="checkFlag.link" class="right-main right-main-link">
                                <div class="extra-info">
                                    <div>{{extraLink.text}}</div>
                                    <div>{{extraLink.desc}}</div>
                                    <div>{{extraLink.sugg}}</div>
                                </div>
                                <el-button @click="editExtraLink" :plain="true" size="small" class="edit-btn"><i class="iconfont icon-edit "></i> 编辑</el-button>
                           </div>
                       </li>
                        <li>
                            <div class="left-title">
                                <el-checkbox v-model="checkFlag.tel"></el-checkbox>
                                <span> 电话</span>
                                <el-tooltip content="附加电话信息，客户可以通过致电与您的商家直接取得联系" placement="top" >
                                    <i class="iconfont icon-tip"></i>
                                </el-tooltip>
                            </div>
                            <div class="right-main">
                                <el-form-item v-if="checkFlag.tel" prop="tel" label-width="0px"
                                              :rules="[{required: true, message: '勾选后该项为必填项', trigger: 'blur'}]">
                                    <el-input class="extra-tel" v-model="adCreate.tel" @blur="checkTel" placeholder="电话号码">
                                        <el-select class="country-code" v-model="adCreate.code" slot="prepend" placeholder="请选择国家/地区" >
                                            <el-option v-for="(item,index) in countryCodeList" :key="item.code" :label="item.name" :value="index"></el-option>
                                        </el-select>
                                    </el-input>
                                    <span class="adc-tips"> {{extraTel}}</span>
                                </el-form-item>
                            </div>
                        </li>
                        <li>
                            <div class="left-title">
                                <el-checkbox v-model="checkFlag.info"></el-checkbox>
                                <span> 宣传信息</span>
                                <el-tooltip content="在您的广告下方显示诸如“免费送货”或“提供全天候的客户服务”之类的说明文字，吸引用户详细了解您提供的产品或服务" placement="top" >
                                    <i class="iconfont icon-tip"></i>
                                </el-tooltip>
                            </div>
                            <div class="right-main">
                                <el-form-item v-if="checkFlag.info" prop="info" label-width="0px"
                                              :rules="[{required: true, message: '勾选后该项为必填项', trigger: 'blur'}]">
                                    <el-input class="lengthLimit" v-model="adCreate.info" @input="handleStringLen(adCreate.info,'exInfoLen',24,'adCreate.info')" :maxlength="exInfoLen" placeholder="宣传内容"></el-input>
                                    <span class="adc-tips stringCount"> {{adCreate.info | returnLen24}}</span>
                                </el-form-item>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <el-form-item prop="name" label="广告名称" label-width="102px">
                <el-input class="lengthLimit" v-model="adCreate.name"  @input="handleStringLen(adCreate.name,'adNameLen',50,'adCreate.name')" :maxlength="adNameLen"></el-input><span class="adc-tips stringCount"> {{adCreate.name | returnLen50}}</span>
                <div class="gg-ab-test" v-show="totalAdPage > 1"><span class="iconfont icon-adapart" style="color: #b4c1c8"></span> <span style="color: #333"> ABtest广告</span>：根据广告内容的不同拆分成多个广告，可以看哪个广告效果更好，不影响总预算<br>
                    <span style="color: #333">Google拆分广告：</span><span class="current">{{totalAdPage}}</span>个
                </div>
            </el-form-item>
            <el-form-item v-if="edit == 'edit-ad'" label="">
                <div class="edit-ad-tips">注意：对广告所做的任何修改都会移除原来的广告，并创建新的广告，新的广告会被提交并重新审核。</div>
                <el-button @click="updateAd('cancel')" class="bd-draft-btn" type="primary">取消</el-button>
                <el-button v-show="!adPostStatus" @click="updateAd('save')" class="bd-next-btn" type="primary">保存</el-button>
                <el-button v-show="adPostStatus" class="bd-next-btn" type="primary" :loading="true">保存中</el-button>
            </el-form-item>
            <el-form-item v-if="edit != 'edit-ad'" label="">
                <el-button @click="nextStep('draft')" v-show="!adDraftStatus" class="bd-draft-btn" :disabled="adPostStatus" type="primary">完成并暂停广告系列</el-button>
                <el-button v-show="adDraftStatus" class="bd-draft-btn" type="primary" :loading="true">保存中</el-button>
                <el-button v-show="!adPostStatus" @click="nextStep('post')" :disabled="adDraftStatus" class="bd-next-btn" type="primary">保存并完成</el-button>
                <el-button v-show="adPostStatus" class="bd-next-btn" type="primary" :loading="true">发布中</el-button>
            </el-form-item>
        </el-form>

        <el-dialog title="编辑附加链接" v-model="dialogExtraLink" @close="cancelExtraLink" class="extra-link-dialog">
            <el-form ref="extraLink" :model="extraLink" :rules="linkRules" label-position="right" label-width="126px">
                <el-form-item label="链接文字" prop="text">
                    <el-input class="lengthLimit" v-model="extraLink.text" @input="handleStringLen(extraLink.text,'exTextLen',24,'extraLink.text')" :maxlength="exTextLen" ></el-input>
                    <span class="adc-tips stringCount"> {{extraLink.text | returnLen24}}</span>
                </el-form-item>
                <el-form-item label="最终到达网址" prop="link">
                    <el-input v-model="extraLink.link" @blur="checkUrl(extraLink.link)" placeholder=" "></el-input>
                </el-form-item>
                <el-form-item label="广告内容描述" prop="desc">
                    <el-input class="lengthLimit" v-model="extraLink.desc" @input="handleStringLen(extraLink.desc,'exDescLen',34,'extraLink.desc')" :maxlength="exDescLen"></el-input>
                    <span class="adc-tips stringCount"> {{extraLink.desc | returnLen34}}</span>
                </el-form-item>
                <el-form-item label="建议" prop="sugg">
                    <el-input class="lengthLimit" v-model="extraLink.sugg" @input="handleStringLen(extraLink.sugg,'exSuggLen',34,'extraLink.sugg')" :maxlength="exSuggLen"></el-input>
                    <span class="adc-tips stringCount"> {{extraLink.sugg | returnLen34}}</span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelExtraLink">取 消</el-button>
                <el-button type="primary" @click="saveExtraLink">保 存</el-button>
            </div>
        </el-dialog>
        <loading :customClass="createLoading" v-show="showLoading" />
    </section>
</template>

<script>
    import Vue from 'vue'
    import axios from '~/plugins/axios'
    import { Row,Col,Switch,Checkbox,CheckboxGroup,Button,Input,Form,FormItem,Select,Option,Carousel,Message,Dialog,Pagination,Tooltip } from 'element-ui'
    import { mapGetters } from 'vuex';
    import GooglePc from '~components/ad-preview/google-pc.vue'
    import GoogleMb from '~components/ad-preview/google-mb.vue'
    import Loading from '~/components/loading.vue'
    import { getRealStringLen } from '~/assets/js/global'

    Vue.use(Row)
    Vue.use(Col)
    Vue.use(Switch)
    Vue.use(Checkbox)
    Vue.use(CheckboxGroup)
    Vue.use(Button)
    Vue.use(Input)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Select)
    Vue.use(Option)
    Vue.use(Carousel)
    Vue.use(Dialog)
    Vue.use(Pagination)
    Vue.use(Tooltip)

    Vue.prototype.$message = Message;

    export default {
        components: {
            GooglePc,
            GoogleMb,
            Loading
        },
        props: {
            'edit': {
                default: null
            },
        },
        data () {
            return {
                createLoading: '',
                showLoading: false,
                adPostStatus: false,
                adDraftStatus: false,
                adCreate: {
                    content: [
                        {
                            link: '',
                            title1: '',
                            title2: '',
                            description: ''
                        }
                    ],
                    preview: '',
                    name: '',
                    tel: '',
                    code: null,
                    info: ''
                },
                countryCodeList: [],
                editIndex: 0,
                linkStatus: true,
                rules: {
                    name: [{ required: true, message: '该项为必填项', trigger: 'blur' }]
                },
                linkRules: {
                    text: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
                    link: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
                    desc: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
                    sugg: [{ required: true, message: '该项为必填项', trigger: 'blur' }]
                },
                adPreviewPlatform: ['桌面版','移动版'],
                currentAdPage: 1,
                totalAdPage: 1,
                showMoreSetting: false,
                dialogExtraLink: false,
                extraLink: {
                    text: '',
                    link: '',
                    desc: '',
                    sugg: ''
                },
                extraLinkTemp: {
                    text: '',
                    link: '',
                    desc: '',
                    sugg: ''
                },
                checkFlag: {
                    link: false,
                    tel: false,
                    info: false
                },
                editData: null,
                adMaxLen: [
                    {
                        title1: 30,
                        title2: 30,
                        desc: 80
                    },
                    {
                        title1: 30,
                        title2: 30,
                        desc: 80
                    },
                    {
                        title1: 30,
                        title2: 30,
                        desc: 80
                    }
                ],
                adNameLen: 50,
                exInfoLen: 24,
                exTextLen: 24,
                exDescLen: 34,
                exSuggLen: 34,
                exNum: 0
            }
        },
        computed: {
            ...mapGetters([
                'adverName',
                'adverPlan',
                'adverUrl',
                'budgetSchedule',
                'editAudienceForm',
                'adverLayout',
                'esimate'
            ]),
            extraTel () {
                let str = '';
                str = this.adCreate.code ? '+'+this.countryCodeList[this.adCreate.code].phone : '';
                str += this.adCreate.tel == null ? '' : this.adCreate.tel;
                return str;
            },
            adPreviewData () {
                return this.adCreate.content[this.currentAdPage-1]
            },
            postData () {
                let postdata = {
                    "archived": false,    //是否为草稿
                    "adSeries": {   //广告系列
                        "name": this.adverName,      //广告系列名称
                        "targetLink": this.adverUrl    //	网站地址

                    },
                    "adGroup": {    //广告组
                        "name": this.budgetSchedule.adsName,   //广告组名称
                        "audience": {    //	受众
                            "languages": this.editAudienceForm.language,    //语言
                            "places": this.editAudienceForm.addr.include,   //地区
                            "exclusedPlaces": this.editAudienceForm.addr.exclude,   //排除地区
                            "keyWords": this.editAudienceForm.keywords.include,    //关键词
                            "exclusedKeyWords": this.editAudienceForm.keywords.exclude   //	排除关键词
                        },
                        "budgetScheduling": {
                            "budget": {     //	预算
                                "isAutoBid": this.budgetSchedule.bidAmount,     //	自动竞价
                                "bidAmount": this.budgetSchedule.clickCost || null,    //自动竞价金额
                                "budgetAmount": this.budgetSchedule.budgetLimit   //	单日预算
                            },
                            "scheduling": {     //排期
                                "isDailyDelivery": this.budgetSchedule.publishTime,   //是否全天投放
                                "timeQuantumList": []   //投放时间段
                            },
                            "startTime": this.budgetSchedule.startTime,     //广告开始时间（用毫秒级的long类型传递）
                            "endTime": this.budgetSchedule.endTime    //	广告结束时间（用毫秒级的long类型传递）
                        },
                        "esimate": this.esimate    //	预计成效
                    },
                    "ad": {     //广告
                        "name": this.adCreate.name,     //广告名称
                        "adContent": this.adCreate.content,    //广告内容
                        "call": {   //附加电话
                            "operateStatus": 'REMOVED',
                            "phone": this.adCreate.tel,
                            "countryCode": ''
                        },
                        "callout": {    //附加宣传
                            "operateStatus": 'REMOVED',
                            "text": this.adCreate.info
                        },
                        "siteLink": {   //附加链接
                            "operateStatus": 'REMOVED',
                            "link": this.extraLink.link,
                            "linkText": this.extraLink.text,
                            "description": this.extraLink.desc,
                            "suggestion": this.extraLink.sugg
                        }
                    }
                };
                if(this.checkFlag.tel) postdata.ad.call.operateStatus = 'ENABLE';
                if(this.checkFlag.info) postdata.ad.callout.operateStatus = 'ENABLE';
                if(this.checkFlag.link) postdata.ad.siteLink.operateStatus = 'ENABLE';

                //分时段投放
                if(!this.budgetSchedule.publishTime) {
                    let tLen = this.budgetSchedule.timeQuantumList.length;
                    let tArr = [];
                    for (let i=0;i<tLen;i++) {
                        this.budgetSchedule.timeQuantumList[i].days.length ? tArr.push(this.budgetSchedule.timeQuantumList[i]) : false;
                    }
                    postdata.adGroup.budgetScheduling.scheduling.timeQuantumList = tArr
                }
                if(this.checkFlag.tel) {
                    postdata.ad.call.countryCode = this.countryCodeList[this.adCreate.code].code
                }

                return postdata
            }
        },
        filters: {
            returnLen30(val) {
                return 30-getRealStringLen(val)
            },
            returnLen80(val) {
                return 80-getRealStringLen(val)
            },
            returnLen24(val) {
                return 24-getRealStringLen(val)
            },
            returnLen34(val) {
                return 34-getRealStringLen(val)
            },
            returnLen50(val) {
                return 50-getRealStringLen(val)
            }
        },
        methods: {
            handleStringLen(val,maxName,len,objName) {
                let realLen = getRealStringLen(val);
                let slen = val.length;
                let maxLen = (realLen-slen) > (len/2) ? len/2 : realLen-slen;
                if(maxName.indexOf('.') != -1) {
                    let arr = maxName.split('.');
                    if(maxName.indexOf('[') != -1) {
                        arr[2] = arr[0].split('[')[1].split(']')[0];
                        arr[0] = arr[0].split('[')[0];
                        this[arr[0]][arr[2]][arr[1]] = len - maxLen;
                    }else {
                        this[arr[0]][arr[1]] = len - maxLen;
                    }
                } else {
                    this[maxName] = len - maxLen;
                }
                if(realLen > len) {
                    let temp = val;
                    let tLen = getRealStringLen(temp);
                    while (tLen > len) {
                        temp = temp.substring(0,temp.length-1);
                        tLen = getRealStringLen(temp);
                    }
                    if(objName.indexOf('.') != -1) {
                        let name = objName.split('.');
                        if(objName.indexOf('[') != -1) {
                            name[2] = name[0].split('[')[1].split(']')[0];
                            name[0] = name[0].split('[')[0];
                            //简单处理
                            this.adCreate[name[0]][name[2]][name[1]] = temp;
                        }else {
                            this[name[0]][name[1]] = temp;
                        }
                    }else {
                        this[maxName] = temp;
                    }
                }
            },

            //自动名称
            autoAdName() {
                let time = new Date();
                let year = (time.getFullYear()+"").substr(2,2);
                let month = (time.getMonth()+1)<10?"0"+(time.getMonth()+1):(time.getMonth()+1)+"";
                let day = time.getDate()<10?"0"+time.getDate():time.getDate()+"";
                let hour = time.getHours()<10?"0" + time.getHours() : time.getHours();
                let minu = time.getMinutes()<10?"0" + time.getMinutes() : time.getMinutes();
                this.adCreate.name = 'default-'+year+month+day+hour+minu;
            },
            getAdData() {
                this.$store.dispatch('getGoogleAd',{localAdId: this.$route.query.localAdId,localSeriesId: this.$route.query.localSeriesId})
                    .then(res => {
                        if(res.data.success) {
                            this.editData = res.data.data;
                            this.initAdData(this.editData)
                        }
                    })
            },
            initAdData(data) {
                this.adCreate.name = data.name;
                //广告文字
                this.adCreate.content[0].link = data.adContent.link;
                this.adCreate.content[0].title1 = data.adContent.title1;
                this.adCreate.content[0].title2 = data.adContent.title2;
                this.adCreate.content[0].description = data.adContent.description;
                //附加电话
                if(data.call && data.call.operateStatus == 'ENABLE') {
                    this.showMoreSetting = true;
                    this.checkFlag.tel = true;
                    this.adCreate.tel = data.call.phone;
                    this.adCreate.code = data.call.countryCode;
                    for(let i=this.countryCodeList.length-1;i>=0;i--) {
                        if(data.call.countryCode == this.countryCodeList[i].code) {
                            this.adCreate.code = i;
                            break
                        }
                    }
                }
                //附加信息
                if(data.callout && data.callout.operateStatus == 'ENABLE') {
                    this.showMoreSetting = true;
                    this.checkFlag.info = true;
                    this.adCreate.info = data.callout.text
                }
                //附加链接
                if(data.siteLink && data.siteLink.operateStatus == 'ENABLE') {
                    this.showMoreSetting = true;
                    this.checkFlag.link = true;
                    this.extraLink.link = data.siteLink.link;
                    this.extraLink.text = data.siteLink.linkText;
                    this.extraLink.desc = data.siteLink.description;
                    this.extraLink.sugg = data.siteLink.suggestion
                }

            },
            plusContent() {
                if(this.adCreate.content.length < 3) {
                    this.adCreate.content.push({
                        link: this.adverUrl,
                        title1: '',
                        title2: '',
                        description: ''
                    })
                }
                this.editIndex = this.adCreate.content.length -1;
                this.totalAdPage = this.adCreate.content.length;
                this.$store.commit('STEP_ADTEST',{data: this.totalAdPage});
            },
            minusContent() {
                if(this.adCreate.content.length > 1) {
                    this.adCreate.content.splice(this.editIndex,1)
                }
                this.editIndex = 0;
                this.totalAdPage = this.adCreate.content.length;
                this.$store.commit('STEP_ADTEST',{data: this.totalAdPage});
            },
            pageChange(str) {
                if(str === 'next' && this.currentAdPage < this.totalAdPage) {
                    this.currentAdPage++
                }else if(str === 'prev' && this.currentAdPage != 1) {
                    this.currentAdPage--
                }
            },
            editExtraLink() {
                this.dialogExtraLink = true;
                if(this.extraLink.text != '') {
                    this.extraLinkTemp.link = this.extraLink.link;
                    this.extraLinkTemp.text = this.extraLink.text;
                    this.extraLinkTemp.desc = this.extraLink.desc;
                    this.extraLinkTemp.sugg = this.extraLink.sugg
                }
            },
            cancelExtraLink() {
                if(this.extraLinkTemp.text == '') {
                    this.$refs.extraLink.resetFields();
                }else {
                    this.extraLink.link = this.extraLinkTemp.link;
                    this.extraLink.text = this.extraLinkTemp.text;
                    this.extraLink.desc = this.extraLinkTemp.desc;
                    this.extraLink.sugg = this.extraLinkTemp.sugg;
                }
                this.dialogExtraLink = false;
            },
            saveExtraLink() {
                this.$refs.extraLink.validate((valid) => {
                    if (valid) {
                        this.extraLinkTemp.link = this.extraLink.link;
                        this.extraLinkTemp.text = this.extraLink.text;
                        this.extraLinkTemp.desc = this.extraLink.desc;
                        this.extraLinkTemp.sugg = this.extraLink.sugg;
                        this.dialogExtraLink = false;
                        this.$message({
                            type: 'success',
                            message: '附加链接保存成功!'
                        });
                    }else {
                        return false
                    }
                })
            },
            countryCode() {
                this.$store.dispatch('getAllCountryCode')
                    .then(res => {
                        if(res.data.success) {
                            this.countryCodeList = res.data.data;
                            if(this.edit == 'edit-ad' && isNaN(this.adCreate.code)) {
                                for(let i=this.countryCodeList.length-1;i>=0;i--) {
                                    if(this.adCreate.code == this.countryCodeList[i].code) {
                                        this.adCreate.code = i;
                                        break
                                    }
                                }
                            }
                        }
                })
            },
            //电话号码
            checkTel() {
                if(isNaN(this.adCreate.tel)){
                    this.adCreate.tel = '';
                    this.$message({
                        type: 'warning',
                        message: '请输入正确的电话号码，只能包含数字'
                    });
                    return false
                }
                if(this.adCreate.code == null || this.adCreate.code == '') {
                    this.$message({
                        type: 'warning',
                        message: '请选择电话归属国家/地区!'
                    });
                    return false
                }
                return true;
            },
            //校验网址
            checkUrl(link,index) {
                this.$store.dispatch('verifyWebUrl',{webUrl:link})
                    .then(res => {
                        if(!res) {
                            setTimeout(()=>{
                                index != undefined ? this.editIndex = index : true
                            },200)
                            this.linkStatus = false;
                        }else {
                            this.linkStatus = true;
                        }
                    });
            },
            //更新广告
            updateAd(str) {
                if(str == 'cancel') {
                    this.$router.go(-1)
                }else{
                    this.$refs.adCreate.validate((valid) => {
                        if (valid) {
                            if(this.checkFlag.link && this.extraLink.text == ''){
                                this.dialogExtraLink = true;
                                this.$message({
                                    type: 'warning',
                                    message: '已勾选的附加链接为必填项，请完成编辑!'
                                });
                                return false
                            }
                            if(this.checkFlag.tel && !this.checkTel()) {
                                return false
                            }

                            this.createLoading = 'top:50%';
                            this.showLoading = true;
                            this.adPostStatus = true;

                            //更新广告数据
                            this.editData.name = this.adCreate.name;
                            this.editData.adContent = this.adCreate.content[0];
                            this.editData.advance = false;
                            if(this.checkFlag.tel) {
                                this.editData.advance = true;
                                this.editData.call == null ? this.editData.call = {} : false;
                                this.editData.call.operateStatus = 'ENABLE';
                                this.editData.call.phone = this.adCreate.tel;
                                this.editData.call.countryCode = this.countryCodeList[this.adCreate.code].code
                            }
                            if(this.checkFlag.info) {
                                this.editData.advance = true;
                                this.editData.callout == null ? this.editData.callout = {} : false;
                                this.editData.callout.operateStatus = 'ENABLE';
                                this.editData.callout.text = this.adCreate.info
                            }
                            if(this.checkFlag.link) {
                                this.editData.advance = true;
                                this.editData.siteLink == null ? this.editData.siteLink = {} : false;
                                this.editData.siteLink.operateStatus ='ENABLE';
                                this.editData.siteLink.link = this.extraLink.link;
                                this.editData.siteLink.linkText = this.extraLink.text;
                                this.editData.siteLink.description = this.extraLink.desc;
                                this.editData.siteLink.suggestion = this.extraLink.sugg
                            }

                            this.$store.dispatch('updateGgAd',JSON.stringify(this.editData))
                                .then(res => {
                                    this.showLoading = false;
                                    this.adPostStatus = false;
                                    if(res.data && res.data.success) {
                                        this.$message({
                                            type: 'success',
                                            message: '编辑广告成功!'
                                        });
                                        this.$router.go(-1)
                                    }
                                }).catch((err) => {
                                    this.showLoading = false;
                                    this.adPostStatus = false;
                                })
                        }
                    })




                }
            },
            //发布广告
            nextStep(str) {
                let mes = '完成并保存';
                if(str == 'draft') {
                    this.postData.archived = true;
                    mes = '完成并暂停'
                }
                this.$refs.adCreate.validate((valid) => {
                    if (valid) {
                        if(!this.linkStatus) {
                            this.$message({
                                type: 'error',
                                message: '链接有误，请输入正确的网址'
                            });
                            return false;
                        }
                        if(this.checkFlag.link && this.extraLink.text == ''){
                            this.dialogExtraLink = true;
                            this.$message({
                                type: 'warning',
                                message: '已勾选的附加链接为必填项，请完成编辑!'
                            });
                            return false
                        }
                        if(this.checkFlag.tel && !this.checkTel()) {
                            return false
                        }

                        this.createLoading = 'top:50%';
                        this.showLoading = true;
                        str == 'draft' ? this.adDraftStatus = true : this.adPostStatus = true;
                        this.$store.dispatch('ggCreateAd',JSON.stringify(this.postData)).then((res) => {
                            this.showLoading = false;
                            str == 'draft' ? this.adDraftStatus = false : this.adPostStatus = false;
                            if(res.data && res.data.success) {
                                this.$message({
                                    type: 'success',
                                    message: mes + '广告成功!'
                                });
                                this.$store.commit('ISADPOSTDONE',{data: true});
                                this.adPostSuccess(res.data,str)
                            }else {
                                this.$store.commit('ADERRORDATA',{data: res.data.data});
                                if(res && res.data.message != null) {
                                    this.$message({
                                        type: 'error',
                                        message: res.data.message
                                    });
                                }
                            }
                        }).catch((err) => {
                            this.showLoading = false;
                            str == 'draft' ? this.adDraftStatus = false : this.adPostStatus = false;
                        })

                    } else {
                        for(let i=0;i<this.adCreate.content.length;i++) {
                            if(this.adCreate.content[i].link == '' || this.adCreate.content[i].description == '') {
                                this.editIndex = i;
                                break
                            }
                            else if(this.adCreate.content[i].title1 == '' || this.adCreate.content[i].title2 == '') {
                                this.editIndex = i;
                                break
                            }
                        }
                        return false
                    }
                })
            },
            //id,status
            adPostSuccess(id,status) {
                if(status == 'draft') {
                    this.$router.push({path: '/manager/google' });
                }else {
                    this.$router.push({path:  '/manager/google/2'});
                }
                this.$store.commit('ISADPOSTDONE',{data: false});
                return true;
            }
        },
        watch: {
            'checkFlag.link'() {
                if(this.edit != 'edit-ad' || this.exNum) {
                    this.dialogExtraLink = this.checkFlag.link;
                }else {
                    this.exNum++;
                }
            },
            editIndex: function () {
                this.currentAdPage = this.editIndex + 1;
            }
        },
        created() {
            this.autoAdName()
            this.$store.commit('AD_CREATE',{data: this.adCreate});
            this.countryCode();
            //编辑广告
            if(this.edit == 'edit-ad') {
                this.getAdData()
            }
        },
        mounted() {
            this.adCreate.content[0].link = this.adverUrl;
            this.extraLink.link = this.adverUrl
        }
    }
</script>

<style lang="scss" >
    .gg-create{
        div,span,i,ul,li,input,button{
            box-sizing: border-box;
        }
        .color-red{
            color: #ff3526;
        }
        .gg-ab-test{
            padding: 20px 0 0;
            color: #666;
            line-height: 24px;
            span{
                color: #333;
            }
            .current{
                color: #0686f9;
            }
        }
        .ad-form-gg{
            border: 1px solid #eaeef0;
            border-radius: 5px;
            .content-con{
                padding: 13px 15px 12px;
                .el-form-item__error {
                    left: 136px;
                    top: 92%;
                    word-break: keep-all;
                }
            }
            .minus-btn{
                position: relative;
                top: -1px;
            }
        }
        .content-btn-con {
            padding: 13px 15px 12px;
            border-bottom: 1px solid #eaeef0;
            .el-button{
                width: 34px;
                height: 34px;
                border-radius: 2px;
                & + .el-button{
                        margin-left: 16px;
                    }
            }
            .plus-btn{
                background-color: #ffb100;
                border: none;
                font-size: 14px;
            }
            .con-btn{
                border: 1px solid #d5dfe4;
                font-size: 14px;
                color: #666666;
                &.active{
                     border: none;
                     background-color: #0686F9;
                     color: white;
                 }
            }
        }
        .advance-setting{
            .bs-title{
                .label{
                    width: 104px;
                }
            }
            .bs-container {
                padding-left: 114px;
            }
        }
        .adc-box-name{
            font-weight: 500;
        }
        .adc-preview {
            .preview-body{
                min-height: 200px;
            }
        }
        .adc-box-con{
            font-size: 13px;
            color: #666;
            margin: 15px 15px 52px;
            border: 1px solid #eaeef0;
            border-radius: 5px;
            li{
                display: block;
                overflow: hidden;
                height: 50px;
                line-height: 49px;
                & + li{
                        border-top: 1px solid #eaeef0;
                    }
            }
            .left-title{
                float: left;
                width: 119px;
                height: 100%;
                padding-left: 14px;
                line-height: 49px;
                text-align: left;
                border-right: 1px solid #eaeef0;
                color: #666666;
            }
            .edit-btn{
                width: 80px;
                height: 24px;
                padding: 0;
                border-radius: 24px;
                color: #666;
            }
            .extra-info{
                margin-right: 20px;
                float: left;
                div{
                    line-height: 14px;
                    font-size: 12px;
                    color: #999;
                }
            }
            .icon-tip{
                margin: 0 0 0 4px;
                font-size: 12px;
                color: #b0bec5;
            }
            .icon-edit{
                color: #b1bfc6;
            }
            .right-main{
                float: left;
                height: 100%;
                line-height: 34px;
                padding: 5px 15px;
                color: #999999;
                .el-input{
                    width: 320px;
                }
                input{
                    height: 28px;
                    font-size: 12px;
                }
                .el-form-item__error {
                    top: 9px;
                    left: 500px;
                    word-break: keep-all;
                }
                .extra-tel{
                    /*width: 160px;*/
                }
            }
            .right-main-link{

            }
            .country-code{
                color: #333;
                margin-right: 10px;
                width: 130px;
                vertical-align: middle;
                .el-input{
                    width: 150px;
                }
            }
            .el-input{
                vertical-align: middle;
            }
        }
        .edit-ad-tips{
            padding: 10px 0;
            color: #999;
            font-size: 12px;
        }
        .extra-link-dialog .el-dialog{
            min-width: 560px;
            max-width: 600px;
        }
    }

</style>